#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

# Custom modules
from models import Account
from models import Good
from models import Planet
from models import Colony
from models import Warehouse
from models import Unit
#from models import Universe
from models import UnitType
from authentication import get_account_from_user

# Built-in or Google modules
import cgi
import os
import logging
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext.webapp.util import login_required

class AllocateResources(webapp.RequestHandler):
    # loop through all solar systems and planets in each solar system
    # allocating a new set of resources
    def get(self):
        all_planets = Planet.all()
        for planet in all_planets:
            for colony_key in planet.colonies:
                colony = Colony.get(colony_key)
                colony.collectable = True
                colony.put()
        print "Successfully allocated resources."


class AwardGoodsPage(webapp.RequestHandler):

    # Give users new goods based on the planets they control
    def get(self):
        users = Account.all()
        for user in users:
            all = Good.all()
            goods = []
            for good in all:
                goods.append(0)
            for planet in user.planet_set:
                for name in planet.goods:
                    try:
                        # Give them 10 goods per planet
                        goods[all.index(name)] += 10
                    except:
                        logging.error("Couldn't give "+name+" resource")
                        print "Couldn't give "+name+" resource"
            user.update_goods(goods)
            
        print "Successfully awarded resources"
   



                            
class Login(webapp.RequestHandler):

    def get(self):
            template_values = {

            }

            path = os.path.join(os.path.dirname(__file__), 'login.html')
            self.response.out.write(template.render(path, template_values))



            
class ResetGoods(webapp.RequestHandler):

    # Make sure none of the planets and warehouses have deprecated goods
    # Only checks the first good of the planet
    # If it's not on the current list, assigns a random good to the planet
    # Warehouses with bad goods get deleted
    def get(self):
        planets = Planet.all()
        for planet in planets:
            try:
                Good.all().index(planet.goods[0])
            except:
                print "Replacing "+planet.goods[0]
                planet.goods = [Good.get_random_good()]
                planet.put()
                print "Now "+planet.goods[0]
                
        print "Checking warehouses"
        warehouses = Warehouse.all()
        for warehouse in warehouses:
            try:
                Good.all().index(warehouse.good)
                print "Good warehouse: "+warehouse.good
            except:
                print "Bad warehouse: "+warehouse.good
                warehouse.delete()
                
# Give every user without a universe a random universe
class SetUniverse(webapp.RequestHandler):
    def get(self):
        accounts = Account.all()
        for account in accounts:
            if account.universe == None:
                account.set_universe(Universe.random())
                print "Assigned "+str(account.nickname)+" to "+account.universe
                
# Create a new UnitType for the store
class CreateUnit(webapp.RequestHandler):
    def post(self):
        name = self.request.get('name')
        level = self.request.get('level')
        min_attack = self.request.get('min_attack')
        max_attack = self.request.get('max_attack')
        hp = self.request.get('hp')
        range = self.request.get('range')
        type = self.request.get('type')
        price = self.request.get('price')
        upkeep = self.request.get('upkeep')
        desc = self.request.get('desc')
        
        ut = UnitType.create(name, level, min_attack, max_attack, hp, range, type, price, upkeep, desc)
        
        msg = "Unit Type created"
        if (ut == None):
            msg = "Error creating Unit Type"
    
        template_values = {
            'msg':msg
            }
        
        path = os.path.join(os.path.dirname(__file__), 'admin_unit.html')
        self.response.out.write(template.render(path, template_values))
        

    def get(self):
        template_values = {}
        
        path = os.path.join(os.path.dirname(__file__), 'admin_unit.html')
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/admin/award', AwardGoodsPage),
                                      ('/admin/resource_allocation', AllocateResources),
                                      ('/admin/reset_goods', ResetGoods),
                                      ('/admin/login', Login),
                                      ('/admin/universe', SetUniverse),
                                      ('/admin/units/new', CreateUnit),],
                                     debug=True)									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()